package com.yuri.voice.record

import android.content.Context
import android.media.MediaRecorder
import android.os.Bundle
import android.os.Environment
import android.telephony.PhoneStateListener
import android.telephony.TelephonyManager
import android.util.Log
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.yuri.voice.record.databinding.ActivityMainBinding
import java.io.File


class MainActivity : AppCompatActivity() {

    private lateinit var binding: ActivityMainBinding

    private var mediaRecorder:MediaRecorder? = null

    private var mAdapter:MyAdapter? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        requestPermission()

        binding.btnStart.setOnClickListener {
            startRecord()
        }

        binding.btnStop.setOnClickListener {
            stopRecord()
        }

        val layoutManager = LinearLayoutManager(this)
        layoutManager.orientation = LinearLayoutManager.VERTICAL
        binding.recyclerView.layoutManager = layoutManager

        mAdapter = MyAdapter(this)
        binding.recyclerView.adapter = mAdapter

        val telephonyManager = getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
        val phoneStateListener: PhoneStateListener = object : PhoneStateListener() {
            override fun onCallStateChanged(state: Int, phoneNumber: String) {
                Log.d("YURI", "onCallStateChanged: state:$state,phoneNumber:$phoneNumber")
                mAdapter?.addItem("onCallStateChanged: state:$state,phoneNumber:$phoneNumber")
                when (state) {
                    TelephonyManager.CALL_STATE_OFFHOOK -> {
                        mAdapter?.addItem("onCallStateChanged:CALL_STATE_OFFHOOK")
                        startRecord()
                    }
                    TelephonyManager.CALL_STATE_IDLE -> {
                        mAdapter?.addItem("onCallStateChanged:CALL_STATE_IDLE")
                        stopRecord()
                    }
                    TelephonyManager.CALL_STATE_RINGING -> {
                        mAdapter?.addItem("onCallStateChanged:CALL_STATE_RINGING")
                    }
                }
            }
        }
        telephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE)
    }

    private fun startRecord() {
        Log.d("YURI", "startRecord")
        mAdapter?.addItem("startRecord")
        val path = Environment.getExternalStorageDirectory().absolutePath + "/voice.3gpp"
        val file = File(path)
        try {
            mediaRecorder = MediaRecorder()
            mediaRecorder!!.setAudioSource(MediaRecorder.AudioSource.VOICE_COMMUNICATION)
            mediaRecorder!!.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP)
            mediaRecorder!!.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB)
            mediaRecorder?.setOutputFile(file.absolutePath)
            mediaRecorder?.setOnErrorListener { mediaRecorder, what, extra ->
                Log.d("YURI", "onError: what:$what,extra:$extra")
                mAdapter?.addItem("startRecord.onError:what:$what,extra:$extra")
            }
            mediaRecorder?.setOnInfoListener { mediaRecorder, what, extra ->
                Log.d("YURI", "onInfo: what:$what,extra:$extra")
                mAdapter?.addItem("startRecord.onInfo:what:$what,extra:$extra")
            }
            mediaRecorder?.prepare()
            mediaRecorder?.start()
        } catch (e: Exception) {
            e.printStackTrace()
            mAdapter?.addItem("startRecord.error:${e.message}")
        }

    }

    private fun stopRecord() {
        Log.d("YURI", "stopRecord")
        mAdapter?.addItem("stopRecord")
        try {
            mediaRecorder?.stop()
            mediaRecorder?.release()
            mediaRecorder = null
        } catch (e: Exception) {
            e.printStackTrace()
            mAdapter?.addItem("stopRecord.Error:${e.message}")
        }
    }

    private fun requestPermission() {
        XXPermissions.with(this)
//            .permission(Permission.Group.STORAGE)
            .permission(Permission.MANAGE_EXTERNAL_STORAGE)
            .permission(Permission.RECORD_AUDIO)
            .permission(Permission.READ_PHONE_STATE)
            .request(object : OnPermissionCallback {
                override fun onGranted(permissions: List<String>, allGranted: Boolean) {
                    Log.d("YURI", "Permission is granted:")
//                    init()
//                    mMediaPlayFragment?.init()
//                    registerNetworkCallback()
                }

                override fun onDenied(permissions: List<String>, doNotAskAgain: Boolean) {
                }
            })
    }
}